package com.tedu.egweibo2.controller;

import com.tedu.egweibo2.mapper.IUserMapper;
import com.tedu.egweibo2.pojo.dto.UserLoginDTO;
import com.tedu.egweibo2.pojo.dto.UserRegDTO;
import com.tedu.egweibo2.pojo.entity.User;
import com.tedu.egweibo2.pojo.vo.UserVO;
import com.tedu.egweibo2.result.JsonResult;
import com.tedu.egweibo2.result.StatusCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.logging.Logger;

@RestController
@RequestMapping("/v1/users")
@Api(tags = "用户模块")
@Slf4j
public class UserController {
    @Autowired
    private IUserMapper iUserMapper;

    @PostMapping("/reg")
    @ApiOperation("用户注册")
    public JsonResult register(@RequestBody @Validated UserRegDTO userRegDTO){
        if(userRegDTO.getUsername()==null||userRegDTO.getUsername().isEmpty()){
            throw  new RuntimeException("用户名不能为空");
        }
        UserVO verify = iUserMapper.verify(userRegDTO.getUsername());
        if(verify!=null){
            return new JsonResult(StatusCode.USERNAME_EXIST);
        }
        User user = new User();
        BeanUtils.copyProperties(userRegDTO,user);
        user.setCreated(new Date());
        iUserMapper.insert(user);
        log.info("注册成功");
        return JsonResult.success();
    }

    @PostMapping("/login")
    @ApiOperation("用户登录")
    public JsonResult login(@RequestBody UserLoginDTO userLoginDTO,@ApiIgnore HttpSession session){
        User loginUser = iUserMapper.login(userLoginDTO.getUsername());
        if(loginUser==null){
            return new JsonResult(StatusCode.USERNAME_ERROR);
        }
        if(!loginUser.getPassword().equals(userLoginDTO.getPassword())){
            return new JsonResult(StatusCode.PASSWORD_ERROR);
        }
        session.setAttribute("user",loginUser);
        return JsonResult.success();
    }
    @GetMapping("/currentUser")
    @ApiOperation("判断是否处于登录状态")
    public JsonResult currentUser(@ApiIgnore HttpSession session){
        User user = (User)session.getAttribute("user");
        if(user==null){
            return new JsonResult(StatusCode.NOT_LOGIN);
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user,userVO);
        return JsonResult.success(userVO);

    }

    @GetMapping("/logout")
    @ApiOperation("退出登录")
    public void logout(@ApiIgnore HttpSession session){
        session.removeAttribute("user");
    }

}
